<template>
	<view>
		<view class="cart">
			<view class="content">
				<label v-for="(item, index) in list" :key="index">
					<view class="list">
						<view class="left">
							<checkbox v-bind:checked="item.isSelect" @click="item.isSelect=!item.isSelect"></checkbox>
							<image :src="item.image" class="image"></image>
						</view>
						<view class="center">
							<view class="name">
								{{item.name}}
							</view>
							<view class="count">
								数量：
								<u-number-box v-model="item.num" :min="1" :max="100"></u-number-box>
							</view>
							<view class="price">
								价格：{{item.price}}元
							</view>
						</view>
						<view class="delBtn">
							<button @click="delPro(item.id)">
								<u-icon name="trash-fill" size="38"></u-icon>
							</button>
						</view>
					</view>
				</label>
			</view>
			<!-- 底部导航栏 -->
			<view class="tabbar">
				<view class="selAll">
					<checkbox-group>
						<checkbox @click="selectProduct(isSelectAll)" v-bind:checked="isSelectAll" />全选
					</checkbox-group>
				</view>
				<view class="totalPrice">
					总价：{{getTotal.totalPrice}}元
				</view>
			</view>
			<view class="pay" @click="payment()">
				付款
			</view>
		</view>
		<view v-show="isShow" class="title">
			<u-empty text="购物车为空" mode="car"></u-empty>
		</view>
	</view>
</template>

<script>
	import axios from "axios";
	import {
		mapGetters
	} from 'vuex';
	export default {
		data() {
			return {
				list: [], //列表数据
				isShow: false,
				date: new Date().toISOString(),
				isSelect: false
				// isSelectList: [],
				// templist: []
			}
		},
		onReady() {
			this.getList()
		},
		computed: {
			userId() {
				return this.$store.getters.getId;
			},
			rechargeAmount() {
				return this.$store.getters.rechargeAmount;
			},
			isSelectAll() {
				//如果List中每一条数据的isSelect都为true，返回true，否则返回false;
				return this.list.every(
					function(val) {
						return val.isSelect
					});
			},
			getTotal() {
				var prolist = this.list.filter(function(val) {
						return val.isSelect
					}),
					totalPri = 0;
				for (var i = 0, len = prolist.length; i < len; i++) {
					totalPri += prolist[i].price * prolist[i].num;
				}
				return {
					totalPrice: totalPri
				}
			}
		},
		methods: {
			dateFormat(time) {
				let date = new Date(time);
				let year = date.getFullYear();
				// 在日期格式中，月份是从0开始的，因此要加0，使用三元表达式在小于10的前面加0，以达到格式统一  如 09:11:05
				let month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
				let day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
				let hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
				let minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
				let seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
				// 拼接
				return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
				// return year + "-" + month + "-" + day;
			},
			selectProduct(_isSelect) {
				//遍历List，全部取反
				for (var i = 0, len = this.list.length; i < len; i++) {
					this.list[i].isSelect = !_isSelect;
				}
			},
			delPro(id) {
				axios.post('/api/shop/DelshopCart', {
					id: id
				}).then(function(res) {
					uni.showToast({
						title: '删除成功',
					});
				})
				this.getList();
			},
			updrechargeAmount() {
				//钱包扣款
				uni.request({
					url: '/api/recharge/addRechrage',
					data: {
						rechargeAmount: -(this.getTotal.totalPrice),
						rechargeTime: this.dateFormat(this.date),
						userId: this.userId
					},
					method: 'POST',
					success: (res) => {},

				})
			},
			payment() {
				if (this.getTotal.totalPrice == 0 || this.getTotal.totalPrice == null) {
					uni.showToast({
						title: "您还未选择商品",
						icon: "error",
					})
				} else {
					let rechargeAmount = uni.getStorageSync("rechargeAmount")
					if (isNaN(this.rechargeAmount) == true) {
						uni.showToast({
							title: '暂未充值',
							icon: 'error'
						})
					} else {
						if (this.rechargeAmount >= this.getTotal.totalPrice) {
							uni.showLoading({
								title: '付款中'
							});
							uni.request({
								url: '/api/order/insertOrder',
								data: {
									product: JSON.stringify(this.list),
									userId: this.$store.getters.getId,
									totalPrice: this.getTotal.totalPrice,
									creatTime: this.dateFormat(this.date)
								},
								method: "POST",
								success: (res) => {
									this.updrechargeAmount();
									//删除所选购物车
									this.list = this.list.filter(function(item) {
										return !item.isSelect
									})
									setTimeout(() => {
										uni.showToast({
											title: "付款成功",
											icon: "success",
										})
										uni.hideLoading()
									}, 1500)
								}
							})
						} else {
							uni.showModal({
								title: '余额不足',
								content: '是否前去充值？',
								cancelText: "取消", // 取消按钮的文字  
								confirmText: "确认", // 确认按钮的文字  
								showCancel: true, // 是否显示取消按钮，默认为 true
								confirmColor: '#f55850',
								cancelColor: '#39B54A',
								success: (res) => {
									if (res.confirm) {
										uni.navigateTo({
											url: "../my/myBag"
										})
									}
								}
							})
						}
					}

				}
			},
			getList() {
				var _this = this;
				axios.post('/api/shop/shopCartDeatil', {
					userId: this.$store.getters.getId
				}).then(function(res) {
					_this.list = res.data
					/*赋值，是否选中*/
					_this.list.map(function(item) {
						_this.$set(item, 'isSelect', true);
					})

					if (res.data.length == 0) {
						_this.isShow = true
					} else {
						_this.isShow = false
					}
				}).catch(function(err) {
					console.log(err)
				})
			}
		}


	}
</script>

<style lang="scss" scoped>
	page {
		background: #f1e8e7;
	}

	.btn {
		height: 18px;
		width: 18px;
	}

	uni-button {
		display: inline-block !important;
		line-height: 18px !important;
		padding: 0 !important;
	}

	.title {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
	}

	.content {
		width: 700rpx;
		margin: 0 auto 180rpx;
	}

	.list {
		width: 702rpx;
		height: 210rpx;
		background: #f9f9f9;
		box-shadow: 0 8rpx 16rpx 0 rgba(83, 66, 49, 0.08);
		border-radius: 24rpx;
		margin-top: 32rpx;
		display: flex;
		justify-content: space-around;
		align-items: center;
	}

	.left {
		display: flex;
		justify-content: space-around;
		align-items: center;
	}

	.image {
		width: 136rpx;
		height: 136rpx;
		margin-left: 10rpx;
		border-radius: 8%;
	}

	.tabbar {
		background: #f9f9f9;
		height: 108rpx;
		display: flex;
		align-items: center;
		width: 80%;
		position: fixed;
		bottom: 45px;
	}

	.selAll {
		margin-left: 10px;
	}

	.totalPrice {
		margin-left: 120px;
	}

	.pay {
		background: #6adae9;
		height: 108rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		/*垂直居中*/
		width: 20%;
		position: fixed;
		bottom: 45px;
		right: 0;
	}
</style>
